package com.wyj.event;

import com.alibaba.fastjson.JSONObject;
import com.wyj.pojo.Message;
import com.wyj.pojo.User;
import com.wyj.pojo.event;
import com.wyj.service.MessageService;
import com.wyj.service.imp.MessageServiceImp;
import com.wyj.util.CommunityConstant;
import com.wyj.util.MailClient;
import lombok.extern.log4j.Log4j2;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 王永杰
 * @Description 描述该类的做什么用
 * @since 2022/8/18
 */
@Component
@Log4j2
public class EventConsumer implements CommunityConstant {

    @Autowired
    MessageServiceImp messageServiceImp;

    @Autowired
    TemplateEngine templateEngine;

    @Autowired
    MailClient mailClient;


    @KafkaListener(topics = {TOPIC_COMMENT,TOPIC_LIKE,TOPIC_FOLLOW})
    public void handleCommentMessage(ConsumerRecord record) {

        if (record == null || record.value() == null) {
            log.info("消息的内容为空");
        }

        event event = JSONObject.parseObject(record.value().toString(), event.class);

        if (event == null) {
            log.info("消息格式错误");
        }

        //发送站内通知
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);//系统的通知
        message.setToId(event.getEntityUserId());//发送给帖子作者的通知
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());

        //发送站内通知  这里是记录一下event事件当中的一些内容
        Map<String, Object> content = new HashMap<>();
        content.put("userId",event.getUserId());
        content.put("entityType",event.getEntityType());
        content.put("entityId",event.getEntityId());

        if (!event.getData().isEmpty()) {
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }
        message.setContent(JSONObject.toJSONString(content));

        messageServiceImp.addLetter(message);

    }


    //发送邮件 将发送邮件的任务传到消息队列中
    @KafkaListener(topics = {TOPIC_MAIL})
    public void handleSendMail(ConsumerRecord record) {

        if (record == null || record.value() == null) {
            log.info("消息的内容为空");
        }

        event event = JSONObject.parseObject(record.value().toString(), event.class);

        //发送邮件通知

        Map<String, Object> data = event.getData();
        Context context = (Context) data.get("context");
        User user = (User)data.get("user");

        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);

    }


}
